import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:oral_cloud/config/app_config.dart';
import 'package:oral_cloud/config/constant.dart';
import 'package:oral_cloud/generated/l10n.dart';
import 'package:oral_cloud/provider/provider_widget.dart';
import 'package:oral_cloud/ui/widget/ButtonProgressIndicator.dart';
import 'package:oral_cloud/ui/widget/global_widget.dart';
import 'package:oral_cloud/ui/widget/text_field.dart';
import 'package:oral_cloud/view_model/login_model.dart';
import 'package:provider/provider.dart';

import 'login_page.dart';

class ModifyPasswordPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ModifyPasswordPageState();
  }
}

class _ModifyPasswordPageState extends State<ModifyPasswordPage> {
  final double VSpace =
      ScreenUtil.getInstance().setHeight(AppConfig.inputVSpace);
  final _nameController = TextEditingController();
  final _pwdController = TextEditingController();
  final _rePwdController = TextEditingController();
  final _vCodeController = TextEditingController();
  final FocusNode _nodeName = FocusNode();
  final FocusNode _nodePwd = FocusNode();
  final FocusNode _nodeRePwd = FocusNode();
  final FocusNode _nodeVCode = FocusNode();
  GlobalKey<VCodeInputWidgetStatue> vCodeInputKey = GlobalKey();
  GlobalKey<_ChangePwdButtonStatue> changePwdKey = GlobalKey();
  @override
  void dispose() {
    _nameController.dispose();
    _pwdController.dispose();
    _rePwdController.dispose();
    _vCodeController.dispose();
    _nodeName.dispose();
    _nodePwd.dispose();
    _nodeRePwd.dispose();
    _nodeVCode.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _nameController.addListener(_inputLister);
    _pwdController.addListener(_inputLister);
    _rePwdController.addListener(_inputLister);
    _vCodeController.addListener(_inputLister);
    super.initState();
  }

  _inputLister() {
    print(" _inputLister");
    bool enableConfirm = _nameController.text.length > 0 &&
        _pwdController.text.length > 0 &&
        _rePwdController.text.length > 0 &&
        _vCodeController.text.length > 0;
    print("enableConfirm=$enableConfirm");
    bool enableVCode = _nameController.text.length == 11;
    vCodeInputKey?.currentState?.updateEnableVCode(enableVCode);
    changePwdKey?.currentState?.updateEnableConfirm(enableConfirm);

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false, //输入框抵住键盘
      appBar: GlobalAppBar(S.of(context).findPassword).appBar,
      body: Container(
        alignment: Alignment.center,
        child: Container(
          width:  ScreenUtil.getInstance().setHeight(AppConfig.loginContainWidth),
          padding: EdgeInsets.only(
              top: ScreenUtil.getInstance()
                  .setHeight(AppConfig.modifyPwdPaddingTop)),
          child: ProviderWidget2<LoginModel,VCodeModel>(
            model1: LoginModel(),
            model2: VCodeModel(),
            onModelReady: (model1,model2) =>
            _nameController.text = model1.getLoginName(),
            builder: (context, model1,model2, child) {
              return child;
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                MyTextField(
                  fontSize: FontSize.fontSizeXXL,
                  contentPaddingV: ScreenUtil.getInstance().setHeight(AppConfig.contentPadding),
                  focusNode: _nodeName,
                  placeHolder: S.of(context).userName,
                  maxLength: 11,
                  keyboardType: TextInputType.phone,
                  controller: _nameController,
                ),
                SizedBox(height: VSpace),
                MyTextField(
                  fontSize: FontSize.fontSizeXXL,
                  contentPaddingV: ScreenUtil.getInstance().setHeight(AppConfig.contentPadding),
                  focusNode: _nodePwd,
                  placeHolder: S.of(context).password,
                  maxLength: 16,
                  controller: _pwdController,
                  isInputPwd: true,
                ),
                SizedBox(height: VSpace),


                MyTextField(
                  fontSize: FontSize.fontSizeXXL,
                  contentPaddingV: ScreenUtil.getInstance().setHeight(AppConfig.contentPadding),
                  focusNode: _nodeRePwd,
                  placeHolder: S.of(context).rePassword,
                  maxLength: 16,
                  controller: _rePwdController,
                  isInputPwd: true,
                ),
                SizedBox(height: VSpace),
                VCodeInputWidget(vCodeInputKey,_nameController,_vCodeController,_nodeVCode),
                SizedBox(height: ScreenUtil.getInstance().setHeight(AppConfig.btnMarginTop),),
                ChangePwdButton(changePwdKey,_nameController, _pwdController, _rePwdController,
                    _vCodeController),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class VCodeWidget extends StatelessWidget{
  final TextEditingController _nameController;
  final FocusNode _vCodeFocus;
  final TextEditingController _vCodeController;
  final bool enableVCode;
  VCodeWidget(this._vCodeFocus, this._vCodeController, this.enableVCode, this._nameController);
  @override
  Widget build(BuildContext context) {
    var model = Provider.of<VCodeModel>(context);
    return MyTextField(
      focusNode: _vCodeFocus,
      placeHolder: S.of(context).nodeVCode,
      controller: _vCodeController,
      maxLength: 6,
      enableClick: enableVCode,
      fontSize: FontSize.fontSizeXXL,
      keyboardType: TextInputType.phone,
      getVCode: (){
        print('开始调用获取验证码接口');
        model.getVCode(_nameController.text)
            .then((value)  {
          if (value) {
            print('获取验证码接口成功,已发送到手机号:${_nameController.text}上!');
          } else {
            model.showErrorMessage(context);
          }
        });
      },
    );
  }

}


class ChangePwdButton extends StatefulWidget{
  final TextEditingController nameController;
  final TextEditingController pwdController;
  final TextEditingController rePwdController;
  final TextEditingController vCodeController;
  ChangePwdButton(Key key,this.nameController, this.pwdController, this.rePwdController, this.vCodeController,):super(key:key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ChangePwdButtonStatue();
  }

}

class _ChangePwdButtonStatue extends State<ChangePwdButton>{

  bool enableConfirm=false;

  void updateEnableConfirm(bool enableConfirm){
    if(this.enableConfirm==enableConfirm){
      print("------updateEnableConfirm no need setState------");
      return;
    }
    setState(() {
      print("------updateEnableConfirm setState------");
      this.enableConfirm=enableConfirm;
    });
  }


  @override
  Widget build(BuildContext context) {
    var model = Provider.of<LoginModel>(context);
    return CommonButtonWidget(
      height:ScreenUtil.getInstance().setHeight(AppConfig.inputHeight),
      child: model.isBusy
          ? ButtonProgressIndicator()
          : Text(
        S.of(context).actionConfirm,
        style:
        TextStyle(color: Colors.white, fontSize: FontSize.fontSizeL),
      ),
      onPressed: model.isBusy || !enableConfirm
          ? null
          : () {
        if( Comparable.compare(widget.pwdController.text, widget.rePwdController.text)==1){
          showToast(S.of(context).twoPwdDifferent, context: context);
          return;
        }
        model
            .modifyPassword(widget.nameController.text, widget.pwdController.text, widget.vCodeController.text)
            .then((value) {
          if (value) {
            showToast(S.of(context).changePwdSuccess, context: context);
          } else {
            model.showErrorMessage(context);
          }
        });
      },
    );
  }
}
